package com.qiwx.pigeon.data.network;

import android.text.TextUtils;


import com.qiwx.pigeon.Utils.LogUtil;
import com.qiwx.pigeon.Utils.SSlUtiles;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DownloadHttpClient {

    public static OkHttpClient client;
    private static final int DEFAULT_TIMEOUT = 30*1000;

    private DownloadHttpClient() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    private static void create() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addNetworkInterceptor(new CacheInterceptor())
                .addInterceptor( new CustomerOkHttpClient.LoggingInterceptor())
                .addInterceptor(new ParamsInterceptor())
                .retryOnConnectionFailure(true)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
        client = builder.build();
    }

    public static OkHttpClient getClient() {
        if (client == null) {
            create();
        }
        return client;
    }

    /**
     * Fresco 加载图片专用 为了支持Https要要对Fresco配置OkHttpClient
     * @return
     */
    public static OkHttpClient getFrescoOkHttpClient(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        builder .hostnameVerifier(new SSlUtiles.TrustAllHostnameVerifier());
        builder.sslSocketFactory(SSlUtiles.createSSLSocketFactory());
        return builder.build();
    }

    static class  CacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);

            String cacheControl = request.cacheControl().toString();
            if (TextUtils.isEmpty(cacheControl)) {
                cacheControl = "public, max-age=60 ,max-stale=2419200";
            }
            return response.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        }
    };

    static class ParamsInterceptor implements Interceptor{
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request.Builder builder1 = request.newBuilder();
            int userId = 0;
//            User user = AppContext.getContext().getUser();
////            if(user!=null){
////                userId = user.getUserId();
////            }
            if (request.method().toUpperCase().equals("POST")) {
                builder1.url(request.url().url() + "?userId=" +(userId==0?"": String.valueOf(userId)));
                builder1.addHeader("X-Requested-With", "XMLHttpRequest");
                builder1.tag(builder1.tag(null).build());
            } else {
                builder1.addHeader("X-Requested-With", "XMLHttpRequest");
            }
            builder1.addHeader("X-Requested-With", "XMLHttpRequest");
            Request request1 = builder1.build();
            return chain.proceed(request1);
        }

    }


    static class LoggingInterceptor2 implements Interceptor {
        private static final String TAG = "OkHttpManger";
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request(); //request还有其他方法没有用
            RequestBody body = request.body();//release 版 必须取消日志
            if(body instanceof FormBody){
                FormBody formBody = (FormBody) body;
                int size = formBody.size();
                if(size>0){
                    StringBuffer sb = new StringBuffer();
                    sb.append("{");
                    for (int i = 0; i < size; i++) {
                        String name = formBody.name(i);
                        String value = formBody.value(i);
                        sb.append(name+":"+value);
                        if(i<size-1){
                            sb.append(",");
                        }
                    }
                    sb.append("}");
                    LogUtil.e(TAG, String.format("请求参数:\n %s", sb.toString()));
                }
            }
            long t1 = System.nanoTime();
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            String responseString = new String(response.body().bytes());
            if(!TextUtils.isEmpty(responseString)){
                LogUtil.e(TAG, String.format("响应行: %s", response.toString())
                        + "\n"
                        + String.format("Access Server in %.1fms ,返回值: %s", (t2 - t1) / 1e6d, responseString));
            }else{
                responseString = "null";
            }
            return response.newBuilder().body(ResponseBody.create(response.body().contentType(), responseString)).build();
        }
    }


}
